package com.zhiqiang.nativeplayer.controller;

import com.zhiqiang.nativeplayer.bean.ResourceDto;
import com.zhiqiang.nativeplayer.handler.FileLoadHandler;
import com.zhiqiang.nativeplayer.handler.NonStaticResourceHttpRequestHandler;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/** file resource controller
 * author：paul
 * date：Created in 18:30 2022/11/21
 */
@RestController
@AllArgsConstructor
public class FileRestController {

    @Autowired
    private NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    /**
     * 预览视频文件, 支持 byte-range 请求
     */
    @CrossOrigin
    @GetMapping("/video")
    public void videoPreview(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String serialId = request.getParameter("serialId");
        ResourceDto dto = FileLoadHandler.getBySerialId(serialId);

        if(dto == null){
            return;
        }

        //TODO file processing
        Path filePath = Paths.get(dto.getUrl());
        if (Files.exists(filePath)) {
            String mimeType = Files.probeContentType(filePath);
            if (mimeType == null || mimeType.trim().length()==0) {
                response.setContentType(mimeType);
            }
            request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }
}
